package com.xkcyy.one.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xkcyy.one.entity.Script;
import com.xkcyy.one.exception.BusinessException;
import com.xkcyy.one.mapper.ScriptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 脚本服务类
 * 
 * @author yuand
 */
@Service
public class ScriptService {

    private final ScriptMapper scriptMapper;
    private final ToolService toolService;

    @Autowired
    public ScriptService(ScriptMapper scriptMapper, ToolService toolService) {
        this.scriptMapper = scriptMapper;
        this.toolService = toolService;
    }

    /**
     * 获取所有脚本
     *
     * @return 脚本列表
     */
    public List<Script> getAllScripts() {
        return scriptMapper.selectList(null);
    }

    /**
     * 根据用户ID获取脚本列表
     *
     * @param userId 用户ID
     * @return 脚本列表
     */
    public List<Script> getScriptsByUserId(Long userId) {
        LambdaQueryWrapper<Script> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Script::getUserId, userId);
        return scriptMapper.selectList(queryWrapper);
    }

    /**
     * 根据ID获取脚本
     *
     * @param id 脚本ID
     * @return 脚本
     */
    public Script getScriptById(Long id) {
        Script script = scriptMapper.selectById(id);
        if (script == null) {
            throw new BusinessException("脚本不存在，ID: " + id);
        }
        return script;
    }

    /**
     * 创建脚本
     *
     * @param script 脚本
     * @return 创建后的脚本
     */
    public Script createScript(Script script) {
        // 检查名称是否已存在
        LambdaQueryWrapper<Script> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Script::getName, script.getName());
        if (scriptMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException("脚本名称已存在: " + script.getName());
        }

        // 设置默认值
        script.setVersion(1);
        script.setCompiled(false);
        if (script.getPermissionLevel() == null) {
            script.setPermissionLevel(Script.PermissionLevel.LOW);
        }

        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        script.setCreateTime(now);
        script.setUpdateTime(now);

        // 插入脚本
        scriptMapper.insert(script);

        return script;
    }

    /**
     * 更新脚本
     *
     * @param script 脚本
     * @return 更新后的脚本
     */
    public Script updateScript(Script script) {
        // 检查脚本是否存在
        Script existingScript = scriptMapper.selectById(script.getId());
        if (existingScript == null) {
            throw new BusinessException("脚本不存在，ID: " + script.getId());
        }

        // 检查名称是否已被其他脚本使用
        LambdaQueryWrapper<Script> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Script::getName, script.getName())
                .ne(Script::getId, script.getId());
        if (scriptMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException("脚本名称已存在: " + script.getName());
        }

        // 如果内容变更，需要重新编译
        if (!existingScript.getContent().equals(script.getContent())) {
            script.setCompiled(false);
            script.setCompiledContent(null);
            script.setVersion(existingScript.getVersion() + 1);
        } else {
            // 保持版本号和编译状态不变
            script.setVersion(existingScript.getVersion());
            script.setCompiled(existingScript.getCompiled());
            script.setCompiledContent(existingScript.getCompiledContent());
        }

        // 设置更新时间
        script.setUpdateTime(LocalDateTime.now());

        // 更新脚本
        scriptMapper.updateById(script);

        return script;
    }

    /**
     * 删除脚本
     *
     * @param id 脚本ID
     */
    public void deleteScript(Long id) {
        // 检查脚本是否存在
        Script existingScript = scriptMapper.selectById(id);
        if (existingScript == null) {
            throw new BusinessException("脚本不存在，ID: " + id);
        }

        // 检查脚本是否被工具使用
        if (!toolService.getToolsByScriptId(id).isEmpty()) {
            throw new BusinessException("脚本正在被工具使用，无法删除");
        }

        // 删除脚本
        scriptMapper.deleteById(id);
    }

    /**
     * 编译脚本
     *
     * @param id 脚本ID
     * @return 编译后的脚本
     */
    public Script compileScript(Long id) {
        Script script = scriptMapper.selectById(id);
        if (script == null) {
            throw new BusinessException("脚本不存在，ID: " + id);
        }

        // TODO: 调用Java编译器编译脚本
        // 这里应该有一个编译服务，将脚本内容编译成字节码
        // 为了示例，这里直接设置编译成功
        script.setCompiled(true);
        script.setLastCompileTime(LocalDateTime.now());
        script.setUpdateTime(LocalDateTime.now());

        // 更新脚本
        scriptMapper.updateById(script);

        return script;
    }

    /**
     * 根据权限级别获取脚本列表
     *
     * @param permissionLevel 权限级别
     * @return 脚本列表
     */
    public List<Script> getScriptsByPermissionLevel(String permissionLevel) {
        LambdaQueryWrapper<Script> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Script::getPermissionLevel, permissionLevel);
        return scriptMapper.selectList(queryWrapper);
    }
}